package com.itheima.chapter09.io.objectstream;

import java.io.*;
import java.util.ArrayList;

//用对象操作流读写多个对象
public class Case {
    public static void main(String[] args) throws IOException {

        ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream("MyIdeaTest\\case.txt"));
        ObjectInputStream ois =new ObjectInputStream(new FileInputStream("MyIdeaTest\\case.txt"));
        method1(oos,ois);
        //method2(oos, ois);
    }

    private static void method2(ObjectOutputStream oos, ObjectInputStream ois) throws IOException {
        Student s1= new Student("zhangsan",23);
        Student s2= new Student("lisi",56);
        Student s3= new Student("wangwu",32);
        ArrayList<Student> list =new ArrayList<>();
        list.add(s1);
        list.add(s2);
        list.add(s3);
        oos.writeObject(list);

        try {
            System.out.println(ois.readObject());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        ois.close();
    }

    private static void method1(ObjectOutputStream oos,ObjectInputStream ois) throws IOException {
        Student s1= new Student("zhangsan",23);
        Student s2= new Student("lisi",56);
        Student s3= new Student("wangwu",32);
        oos.writeObject(s1);
        oos.writeObject(s2);
        oos.writeObject(s3);
        oos.close();
        Object obj;
        while(true){
            try {
                Object o = ois.readObject();
                System.out.println(o);
            } catch (EOFException e) {
                break;
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        ois.close();
    }
}
